package com.moyun.controller.org;


import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moyun.common.annotation.OperLog;
import com.moyun.common.aspect.BusinessType;
import com.moyun.controller.common.CommonController;
import com.moyun.common.utils.StrUtil;
import com.moyun.model.common.PageDTO;
import com.moyun.model.common.PageParam;
import com.moyun.model.common.PageResult;
import com.moyun.model.common.R;
import com.moyun.model.po.org.SysOrgDeptEntity;
import com.moyun.service.org.SysOrgDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yangboxuan
 * @since 2021-06-01
 */
@Api(tags = "部门")
@RestController
@RequestMapping("/org/sys-org-dept")
public class SysOrgDeptController extends CommonController<Object, SysOrgDeptEntity, Object, String> {
    @Autowired
    private SysOrgDeptService sysOrgDeptEntityService;


    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 带条件的分页查询
     * @Date 2021-06-01
     * @Param [params]
     **/
    @ApiOperation("带条件的分页查询")
    @PostMapping({"/select-condition", "select-tree"})
    @OperLog(operModul = "部门模块", operType = BusinessType.QUERY, operDesc = "带条件的分页查询")
    public R selectCondition(@RequestBody PageParam<SysOrgDeptEntity> params, HttpServletRequest request) {
        PageDTO pageParams = params.getPageParams();
        Page<SysOrgDeptEntity> page = new Page<>(pageParams.getCurrent(), pageParams.getSize());
        SysOrgDeptEntity sysOrgDeptEntity = params.getEntityParams();
        QueryWrapper<SysOrgDeptEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(sysOrgDeptEntity.getOrgClass() != null, "org_class", sysOrgDeptEntity.getOrgClass());
        this.sysOrgDeptEntityService.page(page, queryWrapper);
        long count = this.sysOrgDeptEntityService.count(queryWrapper);
        String requestURI = request.getRequestURI();
        if ("/org/sys-org-dept/select-tree".equals(requestURI)) {
            List<SysOrgDeptEntity> records = page.getRecords();
            List<TreeNode<String>> nodeList = records.stream().map(entity -> {
                // 树节点扩展属性(也叫扩展树结点的属性) 树节点本身属性: id parentId(父节点id) name(名称) weight(权重)
                Map<String, Object> map = new HashMap<>();
                map.put("orgClass", entity.getOrgClass());
                map.put("id", entity.getId());
                map.put("deptFlag", entity.getDeptFlag());
                map.put("deptId", entity.getDeptId());
//            map.put("gmt_modifier", LocalDateTime.now());
                TreeNode<String> treeNode = new TreeNode<String>()
                        .setId(entity.getLevelId())
                        .setParentId(entity.getParentLevelId())
                        .setName(entity.getName())
                        .setWeight(entity.getSortNum())
                        .setExtra(map);
                return treeNode;
            }).collect(Collectors.toList());
            //配置
            TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
            // 自定义属性名 都要默认值的 TreeNode的原有属性名是: id parentId(父节点id) name(名称) weight(权重)
            // 这里改为数据库中存储的字段--实体类属性名
            treeNodeConfig.setIdKey("levelId");
            treeNodeConfig.setParentIdKey("parentLevelId");
            treeNodeConfig.setWeightKey("sortNum");
            treeNodeConfig.setNameKey("name");
            // 最大递归深度
            treeNodeConfig.setDeep(4);
            //转换器
            List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "root", treeNodeConfig,
                    (treeNode, tree) -> {
                        tree.setId(treeNode.getId());
                        tree.setParentId(treeNode.getParentId());
                        tree.setWeight(treeNode.getWeight());
                        tree.setName(treeNode.getName());
                        // 扩展属性 ...
                        tree.putExtra("orgClass", treeNode.getExtra().getOrDefault("orgClass", null));
                        tree.putExtra("id", treeNode.getExtra().getOrDefault("id", null));
                        tree.putExtra("deptId", treeNode.getExtra().getOrDefault("deptId", null));
                        tree.putExtra("deptFlag", treeNode.getExtra().getOrDefault("deptFlag", null));
                    });
            return R.ok(new PageResult(count, treeNodes));
        } else {
            return R.ok(new PageResult<SysOrgDeptEntity>(count, page.getRecords()));
        }
    }

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 带条件的分页查询
     * @Date 2021-06-01
     * @Param [params]
     **/
    @ApiOperation("树查询")
    @PostMapping({"select-condition-tree"})
    @OperLog(operModul = "部门模块", operType = BusinessType.QUERY, operDesc = "树查询")
    public R selectTree(@RequestBody PageParam<SysOrgDeptEntity> params) {
        Page<SysOrgDeptEntity> page = new Page<>(1, -1);
        SysOrgDeptEntity sysOrgDeptEntity = params.getEntityParams();
        QueryWrapper<SysOrgDeptEntity> queryWrapper = new QueryWrapper<>();
        if (sysOrgDeptEntity != null) {
            queryWrapper.eq(sysOrgDeptEntity.getOrgClass() != null, "org_class", sysOrgDeptEntity.getOrgClass());
        }
        this.sysOrgDeptEntityService.page(page, queryWrapper);
        long count = this.sysOrgDeptEntityService.count(queryWrapper);

        List<SysOrgDeptEntity> record = page.getRecords();
        List<SysOrgDeptEntity> records = record.subList(1, 50);
        List<TreeNode<String>> nodeList = records.stream().map(entity -> {
            // 树节点扩展属性(也叫扩展树结点的属性) 树节点本身属性: id parentId(父节点id) name(名称) weight(权重)
            Map<String, Object> map = new HashMap<>();
            map.put("orgClass", entity.getOrgClass());
            map.put("id", entity.getId());
            map.put("deptFlag", entity.getDeptFlag());
            map.put("deptId", entity.getDeptId());
//            map.put("gmt_modifier", LocalDateTime.now());
            TreeNode<String> treeNode = new TreeNode<String>()
                    .setId(entity.getLevelId())
                    .setParentId(entity.getParentLevelId())
                    .setName(entity.getName())
                    .setWeight(entity.getSortNum())
                    .setExtra(map);
            return treeNode;
        }).collect(Collectors.toList());
        //配置
        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        // 自定义属性名 都要默认值的 TreeNode的原有属性名是: id parentId(父节点id) name(名称) weight(权重)
        // 这里改为数据库中存储的字段--实体类属性名
        treeNodeConfig.setIdKey("levelId");
        treeNodeConfig.setParentIdKey("parentLevelId");
        treeNodeConfig.setWeightKey("sortNum");
        treeNodeConfig.setNameKey("name");
        // 最大递归深度
        treeNodeConfig.setDeep(4);
        //转换器
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "root", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId());
                    tree.setParentId(treeNode.getParentId());
                    tree.setWeight(treeNode.getWeight());
                    tree.setName(treeNode.getName());
                    // 扩展属性 ...
                    tree.putExtra("orgClass", treeNode.getExtra().getOrDefault("orgClass", null));
                    tree.putExtra("id", treeNode.getExtra().getOrDefault("id", null));
                    tree.putExtra("deptId", treeNode.getExtra().getOrDefault("deptId", null));
                    tree.putExtra("deptFlag", treeNode.getExtra().getOrDefault("deptFlag", null));
                });
        return R.ok(new PageResult(count, treeNodes));
    }

    /**
     * @return com.moyun.common.web.JsonResult
     * @Author yangboxuan
     * @Description 添加数据
     * @Date 2021-06-01
     * @Param [sysOrgDeptEntity]
     **/
    @ApiOperation("添加数据")
    @PostMapping(value = "/insert")
    @OperLog(operModul = "部门模块", operType = BusinessType.INSERT, operDesc = "添加数据")
    public R insert(@RequestBody SysOrgDeptEntity sysOrgDeptEntity) {
        // 获取父部门的parentid
        String parentLevelId = sysOrgDeptEntity.getParentLevelId();
        QueryWrapper<SysOrgDeptEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_level_id", parentLevelId).orderByDesc("level_id").last("limit 1");
        SysOrgDeptEntity deptDB = this.sysOrgDeptEntityService.getOne(wrapper);
        // 截取数据库中该 parentLevelId 下的 最新levelId 的后三位数字
        String numStr = StrUtil.getString(deptDB.getLevelId());
        sysOrgDeptEntity.setLevelId(parentLevelId + numStr);
        sysOrgDeptEntity.setSortNum(deptDB.getSortNum() + 1);
        boolean flag = this.sysOrgDeptEntityService.save(sysOrgDeptEntity);
        if (flag) {
            return R.ok();
        } else {
            return R.error();
        }
    }


}

